package controllers

import (
	"encoding/json"
	"fmt"
	"time"

	"weiboxs.com/new_h_glasses/enums"
	"weiboxs.com/new_h_glasses/models"
	"weiboxs.com/new_h_glasses/services"
)

type ErpEntryController struct {
	BaseController
}

func (c *ErpEntryController) Prepare() {
	c.BaseController.Prepare()

	c.Data["activeSidebarUrl"] = "/entry/index"
}

func (c *ErpEntryController) Index() {
	c.checkAuthor("entry/index")

	c.Data["deleteBtn"] = c.checkActionAuthor("entry/delete")

	c.display("", "erpentry/index_footerjs.html")
}

func (c *ErpEntryController) DataGrid() {

	c.checkAuthor("entry/index")

	var qs models.ErpEntryQueryParam
	json.Unmarshal(c.Ctx.Input.RequestBody, &qs)

	qs.DepartmentId = c.curUser.DepartmentId
	data, count := models.ErpEntryPageList(&qs)

	c.jsonDataTable(count, data)
}

func (c *ErpEntryController) Edit() {

	c.checkAuthor("entry/edit")

	id, _ := c.GetInt64(":id")

	m := new(models.ErpEntry)

	var err error
	m, err = services.ErpEntryView(id, c.curUser.DepartmentId)
	if err != nil {
		c.pageError(err.Error())
	}
	if m.Auditing != 0 {
		c.pageError("数据不允许编辑")
	}

	if m.DepartmentId != c.curUser.DepartmentId {
		c.pageError("数据不存在")
	}
	c.Data["m"] = m
	c.showErpTypeid()

	_, paymethod, deliverymode := c.erpPublicConfig()
	c.Data["paymethod"] = paymethod
	c.Data["deliverymode"] = deliverymode

	c.display("", "erpentry/edit_footerjs.html")
}

//保存主表信息
func (c *ErpEntryController) Save() {

	ser := services.ErpEntryFormData{}
	ser.UpdatedBy = c.curUser.RealName
	ser.CreatedBy = c.curUser.RealName
	ser.UpdatedAt = time.Now().Unix()
	ser.DepartmentId = c.curUser.DepartmentId
	suppliers, _ := c.GetInt64("suppliers")
	ser.Suppliers = suppliers
	id, _ := c.GetInt64("id")
	ser.DeliveryMode, _ = c.GetInt("DeliveryMode")
	ser.PayMethod, _ = c.GetInt("PayMethod")
	ser.Postage, _ = c.GetFloat("postage")
	if id == 0 {
		ser.CreatedAt = time.Now().Unix()
		ser.Number = fmt.Sprintf("%s", services.CreateEntryNumber())
		insertid, err := ser.ErpEntryFormInsert(1)
		if err != nil {
			c.jsonResult(enums.JRCodeFailed, err.Error(), "")
		}
		c.jsonResult(enums.JRCodeSucc, "ok", insertid)
	} else {
		if err := ser.ErpEntryFormUpdate(); err != nil {
			c.jsonResult(enums.JRCodeFailed, err.Error(), "")
		}
		c.jsonResult(enums.JRCodeSucc, "编辑成功", "")
	}
}

//提交订单
func (c *ErpEntryController) SubmitOrder() {
	entry_id, _ := c.GetInt64("entry_id")
	if entry_id <= 0 {
		c.jsonResult(enums.JRCodeFailed, "参数丢失", "")
	}
	ser := services.ErpEntryFormData{}
	if err := ser.SubmitOrder(entry_id, c.curUser.DepartmentId); err != nil {
		c.jsonResult(enums.JRCodeFailed, err.Error(), "")
	}
	c.jsonResult(enums.JRCodeSucc, "ok", "")
}

//删除采购
func (c *ErpEntryController) Delete() {
	c.checkAuthor("entry/delete")

	id, _ := c.GetInt64("id")
	if id == 0 {
		c.jsonResult(enums.JRCodeFailed, "缺少参数", "")
	}

	err := services.ErpEntryDelete(id)
	if err != nil {
		c.jsonResult(enums.JRCodeFailed, err.Error(), "")
	}

	c.jsonResult(enums.JRCodeSucc, "删除成功", "")
}

//删除临时数据
func (c *ErpEntryController) DeleteTemp() {
	err := services.ErpEntryDeleteTemp(c.curUser.DepartmentId)
	if err != nil {
		c.jsonResult(enums.JRCodeFailed, err.Error(), "")
	}

	c.jsonResult(enums.JRCodeSucc, "删除成功", "")
}

func (c *ErpEntryController) Auditing() {
	c.checkAuthor("entry/auditing")

	id, _ := c.GetInt64(":id")
	entry, err := services.ErpEntryView(id, c.curUser.DepartmentId)
	if err != nil {
		c.pageError("找不到指定的记录")
	}
	c.Data["m"] = entry
	_, paymethod, deliverymode := c.erpPublicConfig()
	c.Data["paymethod"] = paymethod
	c.Data["deliverymode"] = deliverymode

	c.display("", "erpentry/auditing_footerjs.html")
}

func (c *ErpEntryController) SaveAuditing() {
	id, _ := c.GetInt64("entry_id")
	status, _ := c.GetInt("status")
	entry, err := services.ErpEntryView(id, c.curUser.DepartmentId)
	if err != nil {
		c.jsonResult(enums.JRCodeFailed, err.Error(), "")
	}
	if status != 1 && status != 2 {
		c.jsonResult(enums.JRCodeFailed, "参数不正确", "")
	}

	entry.Auditing = status //设置审核状态
	entry.UpdatedAt = time.Now().Unix()
	entry.UpdatedBy = c.curUser.RealName
	ser := services.ErpEntryFormData{}
	if err := ser.ErpEntryAuditing(entry); err != nil {
		c.jsonResult(enums.JRCodeFailed, err.Error(), "")
	}
	c.jsonResult(enums.JRCodeSucc, "操作成功", "")
}

func (c *ErpEntryController) View() {

	c.checkAuthor("entry/index")

	id, _ := c.GetInt64(":id")
	if id == 0 {
		c.pageError("缺少参数")
	}

	entry, err := services.ErpEntryView(id, c.curUser.DepartmentId)
	if err != nil {
		c.pageError("找不到指定的记录")
	}
	c.Data["m"] = entry

	_, paymethod, deliverymode := c.erpPublicConfig()
	c.Data["paymethod"] = paymethod
	c.Data["deliverymode"] = deliverymode

	c.display("", "erpentry/view_footerjs.html")

}

func (c *ErpEntryController) Prints() {

	id, _ := c.GetInt64(":id")
	if id == 0 {
		c.pageError("缺少参数")
	}

	entry, err := services.ErpEntryView(id, c.curUser.DepartmentId)
	if err != nil {
		c.pageError("找不到指定的记录")
	}

	c.Data["m"] = entry

	c.display("", "erpentry/prints_footerjs.html", "shared/layout_print.html")
}

//确认对帐
func (c *ErpEntryController) Reconciliation() {

	id, _ := c.GetInt64("entry_id")
	if err := services.ErpEntryReconciliation(id, c.curUser); err != nil {
		c.jsonResult(enums.JRCodeFailed, err.Error(), "")
	}
	c.jsonResult(enums.JRCodeSucc, "操作成功", "")
}

//选择供应商
func (c *ErpEntryController) SelectSuppliers() {

	_, paymethod, deliverymode := c.erpPublicConfig()
	c.Data["paymethod"] = paymethod
	c.Data["deliverymode"] = deliverymode

	suppliers := models.ErpSuppliersList(&models.ErpSuppliersQueryParam{DepartmentId: c.curUser.DepartmentId})
	c.Data["suppliers"] = suppliers

	c.display("", "erpentry/selectsuppliers_footerjs.html", "shared/layout_dialog.html")
}

//显示lensRangeSlider
func (c *ErpEntryController) LensRangeSlider() {
	entry_id := c.GetString("entry_id")
	goods_id := c.GetString("goods_id")
	c.Data["entry_id"] = entry_id
	c.Data["goods_id"] = goods_id
	c.display("erpentry/lens/lensrangeslider.html", "erpentry/lens/lensrangeslider_footerjs.html", "shared/layout_dialog.html")
}

//显示二维表
func (c *ErpEntryController) LensBivariate() {
	entry_id, _ := c.GetInt64("entry_id")
	goods_id, _ := c.GetInt64("goods_id")
	ranges := c.GetString("ranges")
	middle_id, _ := c.GetInt64("middle_id")

	if c.Ctx.Input.IsPost() {
		goods, _ := models.GetErpProductsById(goods_id, &c.curUser)
		ser := services.ErpEntryFormData{}
		middles := ser.GetMiddleForEntryData(middle_id)
		c.jsonResult(enums.JRCodeSucc, "ok", map[string]interface{}{"goods": goods, "middle": middles})
	}
	c.Data["entry_id"] = entry_id
	c.Data["goods_id"] = goods_id
	c.Data["middle_id"] = middle_id
	c.Data["ranges"] = ranges

	is_detail := c.GetString("is_detail")
	fotterjs := "erpentry/lens/lensbivariate_footerjs.html"
	tempatePage := "erpentry/lens/lensbivariate.html"
	if is_detail == "yes" {
		tempatePage = "erpentry/lens/lensbivariate_detail.html"
		fotterjs = "erpentry/lens/lensbivariate_detail_footerjs.html"
	}

	c.display(tempatePage, fotterjs, "shared/layout_dialog.html")
}

//显示成品镜Range
func (c *ErpEntryController) PresbyopicRangeSlider() {
	entry_id := c.GetString("entry_id")
	goods_id := c.GetString("goods_id")

	c.Data["entry_id"] = entry_id
	c.Data["goods_id"] = goods_id

	c.display("erpentry/presbyopic/rangeslider.html", "erpentry/presbyopic/rangeslider_footerjs.html", "shared/layout_dialog.html")
}

//显示其它
func (c *ErpEntryController) OtherAdd() {
	entry_id := c.GetString("entry_id")
	goods_id, _ := c.GetInt64("goods_id")
	middle_id, _ := c.GetInt64("middle_id")
	if c.Ctx.Input.IsPost() {
		goods, _ := models.GetErpProductsById(goods_id,  &c.curUser)
		ser := services.ErpEntryFormData{}
		middles := ser.GetMiddleForEntryData(middle_id)
		c.jsonResult(enums.JRCodeSucc, "ok", map[string]interface{}{"goods": goods, "middle": middles})
	}
	c.Data["entry_id"] = entry_id
	c.Data["goods_id"] = goods_id
	c.Data["middle_id"] = middle_id

	is_detail := c.GetString("is_detail")
	fotterjs := "erpentry/other/other_footerjs.html"
	tempatePage := "erpentry/other/other.html"
	if is_detail == "yes" {
		tempatePage = "erpentry/other/other_detail.html"
		fotterjs = "erpentry/other/other_detail_footerjs.html"
	}

	c.display(tempatePage, fotterjs, "shared/layout_dialog.html")

}

//药品
func (c *ErpEntryController) DrugsAdd() {
	entry_id := c.GetString("entry_id")
	goods_id, _ := c.GetInt64("goods_id")
	middle_id, _ := c.GetInt64("middle_id")
	if c.Ctx.Input.IsPost() {
		goods, _ := models.GetErpProductsById(goods_id,  &c.curUser)
		ser := services.ErpEntryFormData{}
		middles := ser.GetMiddleForEntryData(middle_id)
		c.jsonResult(enums.JRCodeSucc, "ok", map[string]interface{}{"goods": goods, "middle": middles})
	}
	c.Data["entry_id"] = entry_id
	c.Data["goods_id"] = goods_id
	c.Data["middle_id"] = middle_id

	is_detail := c.GetString("is_detail")
	fotterjs := "erpentry/drugs/drugs_footerjs.html"
	tempatePage := "erpentry/drugs/drugs.html"
	if is_detail == "yes" {
		tempatePage = "erpentry/drugs/drugs_detail.html"
		fotterjs = "erpentry/drugs/drugs_detail_footerjs.html"
	}

	c.display(tempatePage, fotterjs, "shared/layout_dialog.html")

}


//光学镜架
func (c *ErpEntryController) MountingAdd() {
	entry_id, _ := c.GetInt64("entry_id")
	goods_id, _ := c.GetInt64("goods_id")
	middle_id, _ := c.GetInt64("middle_id")
	if c.Ctx.Input.IsPost() {
		goods, _ := models.GetErpProductsById(goods_id,  &c.curUser)
		ser := services.ErpEntryFormData{}
		middles := ser.GetMiddleForEntryData(middle_id)
		c.jsonResult(enums.JRCodeSucc, "ok", map[string]interface{}{"goods": goods, "middle": middles})
	}
	c.Data["entry_id"] = entry_id
	c.Data["goods_id"] = goods_id
	c.Data["middle_id"] = middle_id

	is_detail := c.GetString("is_detail")
	fotterjs := "erpentry/mounting/mounting_footerjs.html"
	tempatePage := "erpentry/mounting/mounting.html"
	if is_detail == "yes" {
		tempatePage = "erpentry/mounting/mounting_detail.html"
		fotterjs = "erpentry/mounting/mounting_detail_footerjs.html"
	}
	c.display(tempatePage, fotterjs, "shared/layout_dialog.html")
}

//保存采购明细
func (c *ErpEntryController) SaveEntryData() {
	c.checkAuthor("entry/index")

	entry_id, _ := c.GetInt64("entry_id")
	goods_id, _ := c.GetInt64("goods_id")
	middle_id, _ := c.GetInt64("middle_id")
	purchase_num, _ := c.GetInt64("purchase_num")
	ranges := c.GetString("ranges")
	dataInfo := c.GetString("dataInfo")
	tmp := &services.TmpSaveErpEntryData{PurchaseNum: purchase_num, MiddleId: middle_id, DepId: c.curUser.DepartmentId, GoodsId: goods_id, EntryId: entry_id, Attribute: ranges, Data: dataInfo}
	ser := services.ErpEntryFormData{}
	if middle_id, err := ser.SaveErpEntryData(tmp, &c.curUser); err != nil {
		c.jsonResult(enums.JRCodeFailed, err.Error(), "")
	} else {
		c.jsonResult(enums.JRCodeSucc, "ok", middle_id)
	}
}

//获取中间表数据
func (c *ErpEntryController) GetMiddleData() {
	entry_id, _ := c.GetInt64("entry_id")
	datas := models.ErpEntryMiddleList(entry_id);
	c.jsonResult(enums.JRCodeSucc, "ok", datas)
}

//删除中间表数据
func (c *ErpEntryController) DeleteMiddleData() {
	middle_id, _ := c.GetInt64("middle_id")
	ser := services.ErpEntryFormData{}
	if err := ser.DeleteMiddleData(middle_id); err != nil {
		c.jsonResult(enums.JRCodeFailed, err.Error(), "")
	}
	c.jsonResult(enums.JRCodeSucc, "ok", "")
}

//采购验收
func (c *ErpEntryController) Acceptance() {
	c.checkAuthor("entry/acceptance")
	c.Data["activeSidebarUrl"] = "/entry/acceptance"
	c.display("", "erpentry/acceptance_footerjs.html")
}

//采购详情
func (c *ErpEntryController) AcceptList() {
	id, _ := c.GetInt64(":id")

	if c.Ctx.Input.IsPost() { //获取需要验收的数据
		entry_id, _ := c.GetInt64("entry_id")
		datas := models.ErpEntryMiddleList(entry_id, 20, 50);
		c.jsonResult(enums.JRCodeSucc, "ok", datas)
	}

	entry, err := services.ErpEntryView(id, c.curUser.DepartmentId)
	if err != nil {
		c.pageError("找不到指定的记录")
	}

	c.Data["m"] = entry
	_, paymethod, deliverymode := c.erpPublicConfig()
	c.Data["paymethod"] = paymethod
	c.Data["deliverymode"] = deliverymode

	c.Data["activeSidebarUrl"] = "/entry/acceptance"
	c.display("", "erpentry/acceptlist_footerjs.html")
}

//按类型获取相应验收采购数据
func (c *ErpEntryController) TakeTypeIdAcceptEntryData() {
	entry_id, _ := c.GetInt64("entry_id")
	typeid, _ := c.GetInt("typeid")
	ser := services.ErpEntryFormData{}
	data := ser.TakeTypeIdGetEntryDataAcceptance(entry_id, typeid, true, c.curUser.DepartmentId)
	c.jsonResult(enums.JRCodeSucc, "ok", data)
}

//保存验收
func (c *ErpEntryController) SvaeAcceptance() {
	entry_id, _ := c.GetInt64("entry_id")
	ser := services.ErpEntryFormData{}
	temp := make([]*services.TempAcceptanceData, 0)
	datatablefull := c.GetString("datatablefull")
	if err := json.Unmarshal([]byte(datatablefull), &temp); err != nil {
		c.jsonResult(enums.JRCodeFailed, "数据转换失败:"+err.Error(), "")
	}
	accept := new(models.ErpAcceptance)
	accept.Entry = &models.ErpEntry{Id: entry_id}
	accept.DepartmentId = c.curUser.DepartmentId
	accept.AcceptanceDate = time.Now().Unix()
	accept.AcceptanceUser = c.curUser.RealName
	if err := ser.SaveAcceptance(accept, temp); err != nil {
		c.jsonResult(enums.JRCodeFailed, err.Error(), "")
	}
	c.jsonResult(enums.JRCodeSucc, "ok", "")
}

//按类型获取相应采购数据
func (c *ErpEntryController) TakeTypeIdGetEntryData() {
	entry_id, _ := c.GetInt64("entry_id")
	typeid, _ := c.GetInt("typeid")
	ser := services.ErpEntryFormData{}
	if typeid == 20 || typeid == 50 || typeid == 70 {
		data := ser.TakeTypeIdAcceptData(entry_id, typeid, c.curUser.DepartmentId)
		c_data := make([]*models.ErpAcceptanceData, 0)
		for k, _ := range data {
			if data[k].AcceptanceNum > data[k].StorageNum {
				c_data = append(c_data, data[k])
			}
		}
		c.jsonResult(enums.JRCodeSucc, "ok", c_data)
	} else {
		c_data := make([]*models.ErpEntryData, 0)
		data := ser.TakeTypeIdGetEntryData(entry_id, typeid, c.curUser.DepartmentId)
		for k, _ := range data {
			if data[k].Amount > data[k].StorageNum {
				c_data = append(c_data, data[k])
			}
		}
		c.jsonResult(enums.JRCodeSucc, "ok", c_data)
	}
}

//采购入库
func (c *ErpEntryController) Warehousing() {
	c.checkAuthor("entry/warehousing")

	if c.Ctx.Input.IsPost() {
		var qs models.ErpEntryQueryParam
		json.Unmarshal(c.Ctx.Input.RequestBody, &qs)
		qs.DepartmentId = c.curUser.DepartmentId
		qs.Auditing = 1
		data, count := models.ErpEntryPageList(&qs)
		c.jsonDataTable(count, data)
	}

	c.Data["activeSidebarUrl"] = "/entry/warehousing"
	c.display("", "erpentry/warehousing_footerjs.html")
}

//入库详情
func (c *ErpEntryController) WarehousingList() {
	c.checkAuthor("entry/warehousing")
	c.Data["activeSidebarUrl"] = "/entry/warehousing"

	id, _ := c.GetInt64(":id")

	if c.Ctx.Input.IsPost() { //获取需要验收的数据
		entry_id, _ := c.GetInt64("entry_id")
		datas := models.ErpEntryMiddleList(entry_id, 20, 50);
		c.jsonResult(enums.JRCodeSucc, "ok", datas)
	}

	entry, err := services.ErpEntryView(id, c.curUser.DepartmentId)
	if err != nil {
		c.pageError("找不到指定的记录")
	}
	if entry.Auditing == 4 {
		c.pageError("已入库订单不允许操作")
	}
	c.Data["m"] = entry
	_, paymethod, deliverymode := c.erpPublicConfig()
	c.Data["paymethod"] = paymethod
	c.Data["deliverymode"] = deliverymode

	c.display("", "erpentry/warehousinglist_footerjs.html")
}

//保存入库
func (c *ErpEntryController) SaveWarehousing() {
	ser := services.ErpEntryFormData{}
	data := make([]*services.TempWarehousingData, 0)
	entry_id, _ := c.GetInt64("entry_id")
	entry, err := services.ErpEntryView(entry_id, c.curUser.DepartmentId)
	if err != nil {
		c.jsonResult(enums.JRCodeFailed, "找不到指定的记录", "")
	}
	if entry.Auditing == 4 {
		c.jsonResult(enums.JRCodeFailed, "已入库订单不允许操作", "")
	}
	var i int
	for i = 0; i <= 7; i++ {
		var datatable string
		if i == 0 {
			datatable = c.GetString("datatable")
		} else {
			datatable = c.GetString(fmt.Sprintf("datatable%d", i))
		}
		t := make([]*services.TempWarehousingData, 0)
		if err := json.Unmarshal([]byte(datatable), &t); err == nil {
			for k, _ := range t {
				data = append(data, t[k])
			}
		}
	}


	if err := ser.SaveWarehousing(&c.curUser, entry, data); err != nil {
		c.jsonResult(enums.JRCodeFailed, err.Error(), "")
	}
	c.jsonResult(enums.JRCodeSucc, "ok", "")
}

//入库查询
func (c *ErpEntryController)  QueryWarehousing () {
	c.checkAuthor("entry/query_warehousing")
	c.Data["activeSidebarUrl"] = "/entry/query_warehousing"
	if c.Ctx.Input.IsPost() {
		var qs models.ErpFlowingQueryParam
		json.Unmarshal(c.Ctx.Input.RequestBody, &qs)
		qs.DepartmentId = c.curUser.DepartmentId
		qs.Typeid = []interface{}{1}
		qs.IsFlushing = 2
		data, count := models.ErpFlowingPageList(&qs, "Entry", "Entry__Suppliers")
		c.jsonDataTable(count, data)
	}

	c.display("", "erpentry/querywarehousing_footerjs.html")
}

//入库明细
func (c *ErpEntryController)  WarehousingDetails () {
	id,_:= c.GetInt64(":id")
	if id == 0 {
		c.pageError("参数不正确")
	}
	if c.Ctx.Input.IsPost() {
		var qs models.ErpFlowingDataQueryParam
		json.Unmarshal(c.Ctx.Input.RequestBody, &qs)
		qs.Department = c.curUser.DepartmentId
		qs.FlowingId = id
		//qs.RelatedSel = []interface{}{"Products", "Acceptance", "Snd"}
		data, count := models.ErpFlowingDataPageList(&qs)
		c.jsonDataTable(count, data)
	}
	c.display("", "erpentry/warehousingdetails_footerjs.html", "shared/layout_dialog.html")
}

//安全库存
func (c *ErpEntryController)  Security () {
	c.checkAuthor("entry/security")

	if c.Ctx.Input.IsPost() {
		var params models.ErpProductsQueryParam
		json.Unmarshal(c.Ctx.Input.RequestBody, &params)
		params.DepartmentId = c.curUser.DepartmentId
		data, total := models.ErpProductsPageList(&params)
		c.jsonDataTable(total, data)
	}
	c.Data["activeSidebarUrl"] = "/entry/security"
	c.showErpTypeid()
	suppliers := models.ErpSuppliersList(&models.ErpSuppliersQueryParam{DepartmentId: c.curUser.DepartmentId})
	c.Data["suppliers"] = suppliers
	c.display("", "erpentry/security_footerjs.html")
}

//生成库存定量
func (c *ErpEntryController)  SecurityConfirm () {
	c.checkAuthor("entry/security")
	products_id, _ := c.GetInt64("product_id")

	if c.Ctx.Input.IsPost() {

	}
	//获取产品名称
	if product, err := models.GetErpProductsById(products_id,  &c.curUser); err != nil {
		c.pageError("找不到对应的产品信息")
	} else {
		c.Data["product"] = product
	}


	c.display("", "erpentry/securityconfirm_footerjs.html", "shared/layout_dialog.html")
}

//保存库存定量
func (c *ErpEntryController)  SecuritySave () {



	c.jsonResult(enums.JRCodeSucc, "ok", "")
}